#pragma once

#include <iostream>
#include <cstring>
#include <cstdlib>
#include "udp_sock.hpp"

const static uint16_t portdefault = 8080;

class UdpServer
{
public:
    UdpServer(uint16_t port = portdefault) : _port(port)
    {
    }
    ~UdpServer() {}

    void Init()
    {
        _sock.Socket();
        _sock.Bind(_port);
    }

    void Start()
    {
        while (true)
        {
            // 1. 接受数据
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);
            std::string msg;
            bool flag = _sock.Recv(&msg, &peer, &len);
            if (!flag)
            {
                continue;
            }
            // 2. 处理数据
            // 2.1 提取用户信息
            std::string peerIp = inet_ntoa(peer.sin_addr);
            uint16_t peerPort = ntohs(peer.sin_port);
            // 2.2 提供echo服务
            std::cout << "client[" << peerIp << ":" << peerPort << "] say:" << msg << std::endl;
            // 3. 发送数据
            std::string echo_msg = msg;
            _sock.Send(echo_msg, peer, len);
        }
    }

private:
    UdpSock _sock;
    uint16_t _port;
};